package com.cqjtu.eecs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cqjtu.eecs.entity.Permission;
import com.cqjtu.eecs.entity.User;
import com.cqjtu.eecs.entity.vo.RouterVo;
import com.cqjtu.eecs.mapper.PermissionMapper;
import com.cqjtu.eecs.mapper.RolePermissionMapper;
import com.cqjtu.eecs.mapper.UserMapper;
import com.cqjtu.eecs.mapper.UserPermissionMapper;
import com.cqjtu.eecs.service.IPermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

/**
 * <p>
 * 权限 服务实现类
 * </p>
 *
 * @author     
 * @since 2022-03-04
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements IPermissionService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserPermissionMapper userPermissionMapper;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    /**
     * 获取当前登录用户的权限路由
     * @param name
     * @return
     */
    @Override
    public Set<RouterVo> getUserPermission(String name) {

        try {
            // 根据用户名查询用户id
            User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", name));
            if (user == null)
                return null;
            Integer uid = user.getUid();

            // 根据uid获取用户特有的权限路由
            Set<RouterVo> routerVoList = new HashSet<>();
            Set<RouterVo> userRouterList = userPermissionMapper.getUserPermission(uid);
            routerVoList.addAll(userRouterList);

            // 根据uid获取用户所属角色的权限路由
            Set<RouterVo> userRoleRouterList = rolePermissionMapper.getUserRolePermission(uid);
            routerVoList.addAll(userRoleRouterList);
            return routerVoList;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
